# 第4章 栈
# 概念
栈是一种后进先出(LIFO)原则的有序集合。新添加或待删除的元素都保存在栈的同一端,称作栈顶,另一端叫栈底。新元素都靠近栈顶,旧元素都接近栈底。
# 数组实现
class StackArray {
constructor() {
this.items = []
}
push(element) {
this.items.push(element)
}
pop() {
return this.items.pop()
}
peek() {
return this.items[this.items.length - 1]
}
isEmpty() {
return this.items.length === 0
}
size() {
return this.items.length
}
clear() {
this.items = []
}
toArray() {
return this.items
}
toString() {
return this.items.toString()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 对象实现
class Stack {
constructor() {
this.count = 0
this.items = {}
}
push(element) {
this.items[this.count] = element
this.count++
}
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
isEmpty() {
return this.count === 0
}
size() {
return this.count
}
clear() {
/* while (!this.isEmpty()) {
this.pop();
} */
this.items = {}
this.count = 0
}
toString() {
if (this.isEmpty()) {
return ""
}
let objString = `${this.items[0]}`
for (let i = 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`
}
return objString
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 保护数据结构内部元素
- 下划线命名约定
class Stack {
constructor() {
this._count = 0
this._items = {}
}
}
1
2
3
4
5
6
2
3
4
5
6
- Symbol 实现类 假的私有属性。
const items=Symbol('stackItems');
class Stack{
constructor(){
this.[_items]=[];
}
}
1
2
3
4
5
6
2
3
4
5
6
- WeakMap 实现类 此种方法可读性不强,但是是真正的私有属性。
const items = new WeakMap()
class Stack {
constructor() {
items.set(this, [])
}
push(element) {
const s = items.get(this)
s.push(element)
}
pop() {
const s = items.get(this)
const r = s.pop()
return r
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 进制转换算法
function baseConverter(decNumber, base) {
const remStack = new Stack()
const digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let number = decNumber
let rem
let baseString = ""
if (!(base >= 2 && base <= 36)) {
return ""
}
while (number > 0) {
rem = Math.floor(number % base)
remStack.push(rem)
number = Math.floor(number / base)
}
while (!remStack.isEmpty()) {
baseString += digits[remStack.pop()]
}
return baseString
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
← 第3章 数组 第5章 队列和双端队列 →